import { Injectable } from "@angular/core";
import { QueryEncoder } from "@angular/http";
declare var jsPDF: any;
declare var html2canvas: any;

import { LocalStorage } from "../../tools/local.storage";
import { SessionStorage } from "../../tools/session.storage";
import notify from "devextreme/ui/notify";
declare var $: any;
/**
 * 工具
 */
export class ParamUtil {
  static sessionStorage: SessionStorage = new SessionStorage();
  static localStorage: LocalStorage = new LocalStorage();
  static queryEncoder: QueryEncoder = new QueryEncoder();

  constructor() {}

  /**
   * 简单json对象装换为查询字符串
   * @Time 2017-12-26
   * @author Zhong Yang
   * @param json 查询Form表单封装成的对象
   */
  static json2Params(json: object): string {
    let retArr: Array<string> = [];
    let ret: string = "";
    for (var p in json) {
      if (typeof json[p] == "function") {
        continue;
      }
      let notNull: boolean =
        json[p] != "" && json[p] != null && json[p] != undefined;
      if (typeof json[p] == "string" && notNull) {
        retArr.push(p + "=" + json[p]);
      } else if (json[p] instanceof Date && notNull) {
        retArr.push(p + "=" + json[p].getTime());
      } else {
        console.log("arry[" + p + "] is not searchFormData property.");
      }
    }
    ret = retArr.join("&");
    return ret;
  }
  
  /**
   * 非空判断
   * @param value 传来的值
   */
  static notNull(value: any): boolean {
    let b = value != null && value != undefined;
    // is string
    if(ParamUtil.isString(value)){
      return b && value.trim() != "";
    }
    // is Array
    else if(ParamUtil.isArray(value)){
      return b;
    }
    // other
    else {
      return b;
    }

  }
  
  /**
   * 空判断
   * @param value 传来的值
   */
  static isNull(value: any): boolean {
    return ParamUtil.notNull(value) == true ? false : true;
  }

  /**
   * 简单json对象装换为查询字符串   日期格式以毫秒数返回到后台
   * @Time 2017-12-26
   * @author Zhong Yang
   * @param json 查询Form表单封装成的对象
   */
  static json2Params1(json: object): string {
    let retArr: Array<string> = [];
    let ret: string = "";
    if (json == null || json == undefined) {
      return ret;
    }

    for (var p in json) {
      if (typeof json[p] == "function") {
        continue;
      }
      let notNull: boolean = ParamUtil.notNull(json[p]),
        isStringOrNumber =
          typeof json[p] == "string" || typeof json[p] == "number";

      // console.log('isStringOrNumber = ',isStringOrNumber);

      // 参数中,只能是字符串,数字,数组类型;
      if (isStringOrNumber && notNull) {
        let v = json[p];
        // while(v.indexOf("&") >= 0){
        //     v = v.replace("&","%2d9c%");
        // }
        if (typeof json[p] == "string") {
          if (v.indexOf("&") >= 0) {
            v = v.replace(/\&/g, "%2d9c%");
          }
        }

        retArr.push(p + "=" + v);
      }
      // 日期控件
      else if (json[p] instanceof Date && notNull) {
        // 方案1: 时间控件默认以: yyyyMMdd输出
        //let d: string = ParamUtil.fmtDateFunc(json[p], 'yyyyMMdd');
        //retArr.push(`${p}=${d}`);
        //方案2: 以毫秒数输出
        retArr.push(p + "=" + json[p].getTime());
      }
      // 数组
      else if (json[p] instanceof Array && notNull && json[p].length) {
        let arrVal: string = json[p].join(",");
        retArr.push(`${p}=${arrVal}`);
      } else {
        notNull &&
          console.log("arry[" + p + "] is not searchFormData property.");
      }
    }
    ret = retArr.join("&");
    return ret;
  }
  

  /**
   * 封装FORM表单数据
   * 简化调用的方法名
   *
   * @param data 只能是序列化的字符串, 或者对象
   */
  static wrapForm(data: any): string {
    let form: any[] = Array<any>();
    let ret = {
      items: [],
      itemCount: 0,
      dicts: [],
      resultHint: "",
    };
    try {
      // 是字符串
      if (typeof data == "string") {
        form = JSON.parse(`${data}`);
      }

      // 是数字
      if (typeof data == "number") {
        throw new Error("is number");
      }
      // 是数组
      else if (data instanceof Array) {
        form = data;
      }
      // 是对象
      else if (typeof data == "object") {
        form = [data];
      }
      let itemCount = form.length;
      let items = form;
      Object.assign(ret, { items, itemCount });
      return JSON.stringify(ret);
    } catch (e) {
      throw e;
    }
  }

  /**
   * 组织查询条件的入参
   * 组装格式如下:
   * {
   *  pageIndex:0,
   *  pageSize:12,
   *  filter:''
   * }
   */
  static loadCondition(loadOptions?: any, formData?: any): string {
    //默认加载方法
    let params: string = "";
    let obj = {
      pageIndex: 1,
      pageSize: 12,
      filter: params,
    };
    try {
      var tmp = formData;
      //当页面初始化调用查询方法时
      if (formData == undefined) {
        // searchForm,此属性loadOptions对象中不存在,存疑
        // tmp = loadOptions.searchForm;
      }
      //组织filter查询条件
      params = ParamUtil.json2Params1(tmp);
    } catch (ee) {
      console.error("json2Params is error", ee);
    }

    let condi: string = "";
    let o: any = {};
    if (loadOptions != null) {
      let pageIndex = loadOptions.skip
        ? loadOptions.skip / loadOptions.take + 1
        : 1;
      let pageSize = loadOptions.take ? Number.parseInt(loadOptions.take) : 15;
      Object.assign(o, obj, {
        pageIndex: pageIndex,
        pageSize: pageSize,
        filter: params,
      });
    }
    condi = JSON.stringify(o);

    let tmpCondi: string = ParamUtil.queryEncoder.encodeValue(condi);
    // console.log('initParam', "params="+condi,tmpCondi);
    return `params=${tmpCondi}`;
  } //loadCondition end

  /**
   * 查询请求参数的封闭
   * 包装对象型的查询参数
   * @param params
   * @param loadOptions
   * @param pageIndex
   * @param pageSize
   */
  static wrapParams(
    params: any,
    loadOptions?: any,
    pageIndex?: number,
    pageSize?: number
  ): string {
    //默认加载方法
    let obj = {
      pageIndex: pageIndex || 1,
      pageSize: pageSize || 15,
      filter: "",
    };

    let tmp: any = {};
    if (
      loadOptions != null &&
      loadOptions.skip != null &&
      loadOptions.take != null
    ) {
      var pageIndex = loadOptions.skip / loadOptions.take + 1;
      var pageSize = Number.parseInt(loadOptions.take);
      tmp = Object.assign({}, obj, { pageIndex, pageSize });
      // console.log('paging = ',{pageIndex,pageSize});
    }
    if (params != null) {
      var filter = ParamUtil.json2Params1(params);
      tmp = Object.assign({}, obj, tmp, { filter });
      // console.log('filter = ',filter,tmp);
    }

    // console.log('tmp = ',tmp);
    let condi = JSON.stringify(tmp);

    let tmpCondi: string = ParamUtil.queryEncoder.encodeValue(condi);
    // console.log('wrapParams', condi,tmpCondi);
    return `params=${tmpCondi}`;
  }

  /**
   * 包装类型表单
   * @param data
   * @returns [
   *  {},  //form data,只能有一个对象
   *  FILE //FILE file,多个文件
   * ]
   */
  static wrapMultiForm(data: any): Array<any> {
    console.log("wrapMultiForm: ", data);

    let form = [],
      tmpObj = {};
    // console.log('data = ',data);

    let isArray = data instanceof Array;
    // 入参类型
    if (isArray == true) {
      data.map((o, idx, self) => {
        // 是文件对象
        if (o instanceof File) {
          form.push(o);
        }
        // 是文件自定义对象
        else if (typeof o == "object" && o["file"] != null) {
          form.push(o);
        }
        // 是数组
        else if (o instanceof Array && o.length > 0) {
          // 判断首元素是否是File对象
          if (o[0] instanceof File) {
            o.map((f) => {
              form.push(f);
            });
          } else {
            tmpObj[a] = o;
          }
        }
        // 是表单对象
        else {
          // clone对象
          Object.assign(tmpObj, o);
        }
      });
      form.push(tmpObj);
      return form;
    }

    // 入参非数组
    for (var a in data) {
      let tmp = data[a];
      if (tmp == null) {
        // 常规属性
        tmpObj[a] = tmp;
        continue;
      }

      let isFile = tmp instanceof File;
      let isFileObj = typeof tmp == "object" && tmp["file"] != null;
      let isFileArr = tmp instanceof Array && tmp.length > 0;
      if (isFile) {
        // FILE类型的
        form.push(tmp);
      }
      // 是个文件对象
      else if (isFileObj) {
        form.push(tmp["file"]);
      }
      // 是个文件数组
      else if (isFileArr) {
        // 判断首元素是否是File对象
        if (tmp[0] instanceof File) {
          tmp.map((f) => {
            form.push(f);
          });
        } else {
          tmpObj[a] = tmp;
        }
      } else {
        // 常规属性
        tmpObj[a] = tmp;
      }
    }
    form.push(tmpObj);

    // console.log('wrapMultiFormParams', condi);
    return form;
  }

  /**
   * 格式化时间
   */
  static fmtDateFunc(d: Date, fmt: string): string {
    let yyyy = `${d.getFullYear()}`,
      yy = `${yyyy.slice(-2)}`,
      MM = `0${d.getMonth() + 1}`.slice(-2),
      dd = `0${d.getDate()}`.slice(-2),
      hh = `0${d.getHours()}`.slice(-2),
      mm = `0${d.getMinutes()}`.slice(-2),
      ss = `0${d.getSeconds()}`.slice(-2);
    let ret = "";
    ret = fmt.replace(/yyyy/g, yyyy);
    ret = ret.replace(/MM/g, MM);
    ret = ret.replace(/dd/g, dd);
    ret = ret.replace(/hh/g, hh);
    ret = ret.replace(/mm/g, mm);
    ret = ret.replace(/ss/g, ss);

    return ret;
  }
  /**
   * 转换表单时间格式
   * @param data
   * @returns form
   */
  static wrapFormTime(opt: any) {
    for (var a in opt) {
      let tmp = opt[a];
      if (tmp instanceof Date && this.notNull(tmp)) {
        let t: string = ParamUtil.fmtDateFunc(tmp, "yyyyMMdd");
        opt[a] = t;
      }
    }

    return opt;
  }

  /**
   * 获取token
   */
  static getToken() {
    let token = ParamUtil.sessionStorage.getJson("token");
    // 测试时使用
    if (token == null) {
      token = {
        tokenId: "02b70b8d-d344-4556-9515-948fd2c5b5aa",
        sysFlag: "100043004",
      };
      ParamUtil.sessionStorage.setJson("token", token);
      return null;
    }
    return token["tokenId"];
  }


  /**
   * 获取UUID
   */
  static getUUID() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (
      c
    ) {
      var r = (Math.random() * 16) | 0,
        v = c == "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  }

    /**
   * 是否是字符串
   */
  static isString(data: any){
    // 是字符串,"string"
    return (typeof data == "string");
  }


  /**
   * 是否是函数
   */
  static isFunction(data: any){
    // 函数
    return (data instanceof Function);
  }
  

  /**
   * 是否是数组
   */
  static isArray(data: any ){
    // 数组
    return (data instanceof Array);
  }


  /**
   * 是否是对象
   */
  static isObject(data: any){
    // 是对象
    return (typeof data == "object");
  }
}
